//
//  Status.swift
//  Super_WeiBo
//
//  Created by 梁超 on 16/3/27.
//  Copyright © 2016年 lc. All rights reserved.
//

import UIKit
import SDWebImage

class Status: NSObject {
     /// 创建时间
    var created_at: String?
        {
        didSet{
            // 例子： Sun Sep 12 14:50:57 +0800 2014
            // 将字符串转换为时间
            let createdDate = NSDate.dateWithStr(created_at!)
            // 获取格式化之后的时间字符串
            created_at = createdDate.descDate
        }
    }
     /// 用户ID
    var id: Int = 0
     ///  微博内容
    var text: String?
     /// 微博来源
    var source: String?
        {
        didSet{
            // 例子: <a href=\"http://app.weibo.com/t/feed/4fuyNj\" rel=\"nofollow\">即刻笔记</a>
            
            // 截取字符串
            if let str = source
            {
                if str == ""
                {
                    return
                }
                
                // 获取开始截取的位置 String 转换为 NSString 方便调用方法
                let startLocation = (str as NSString).rangeOfString(">").location + 1
                // 获取截取的长度
                let length = (str as NSString).rangeOfString("<", options: NSStringCompareOptions.BackwardsSearch).location - startLocation
                // 截取字符串
                source = "来自: " + (str as NSString).substringWithRange(NSMakeRange(startLocation, length))
            }
        }
    }
    /// 保存微博配图URL
    var storedPicURLS: [NSURL]?
    /// 保存微博配图大图URL
    var storedLargePicURLS: [NSURL]?
    
    /// 配图数组
    var pic_urls: [[String : AnyObject]]?
        {
        didSet{
            // 初始化数组
            storedPicURLS = [NSURL]()
            storedLargePicURLS = [NSURL]()
            
            // 遍历取出图片路径字符串
            for dict in pic_urls!
            {
                if let urlstr = dict["thumbnail_pic"] as? String
                {
                    // 转化为 NNSURL 存入数组
                    storedPicURLS?.append(NSURL(string: urlstr)!)
                    
                    // 处理大图URL
                    let largeStr = urlstr.stringByReplacingOccurrencesOfString("thumbnail", withString: "large")
                    // 存入大图URL数组
                    storedLargePicURLS?.append(NSURL(string: largeStr)!)
                }
            }
        }
    }
    /// 用户信息
    var user : User?
    
    /// 转发微博
    var retweeted_status : Status?
    
    /// 定义一个计算属性，用于返回原创或转发配图URL数组(如果一条微博有转发，原创就没有配图)
    var pictureURLs: [NSURL]?
    {
        return retweeted_status != nil ? retweeted_status?.storedPicURLS : storedPicURLS
    }
    
    /// 定义一个计算属性，用于返回原创或转发配图"大图"URL数组(如果一条微博有转发，原创就没有配图)
    var largePictureURLs: [NSURL]?
    {
        return retweeted_status != nil ? retweeted_status?.storedLargePicURLS : storedLargePicURLS
    }
    
    /**
     请求微博数据
     */
    class func loadStatuses(since_id: Int, max_id: Int, finished: (model: [Status]?, error: NSError?) -> ()){
        
        let path = "2/statuses/home_timeline.json"
        var params = ["access_token" : UserAccount.loadAccount()!.access_token!]
        
        // 下拉刷新
        if since_id > 0
        {
            params.updateValue("\(since_id)", forKey: "since_id")
        }
        
        // 上拉加载更多
        if max_id > 0
        {
            params.updateValue("\(max_id - 1)", forKey: "max_id")
        }
        
        NetworkTools.shareNetworkTools().GET(path, parameters: params, success: { (_, JSON) in
            // 转换模型
            let model = dictToModels(JSON!["statuses"] as! [[String: AnyObject]])
            
            // 缓存微博图片 同时把闭包传递给
            cacheStatusImages(model, finished: finished)
            
            }) { (_, error) in
                // 通过闭包返回错误信息
                finished(model: nil, error: error)
        }
    }
    
    /**
     缓存微博图片
     
     - parameter modelList: 微博数据模型数组
     - parameter finished:  回调闭包
     */
    class func cacheStatusImages(modelList: [Status], finished: (model: [Status]?, error: NSError?) -> ())
    {
        if modelList.count == 0
        {
            finished(model: modelList, error: nil)
            return
        }
        
        // 创建一个组
        let imgDownGroup = dispatch_group_create()
//        print("add".cacheDir())
        
        // 缓存图片
        for status in modelList
        {
            // Swift2.0新语法 守护，如果 guard 后面表达式为 nil 就执行 else后面的语句 (status.storedPicURLS != nil)
            guard status.pictureURLs != nil else
            {
                continue
            }
            
            // 判断配图数组中是否有值 如果没有进入下次循环
            if status.storedPicURLS!.count == 0
            {
                continue
            }
            
            for url in status.pictureURLs!
            {
                // 将当前下载操作添加到『组』中
                dispatch_group_enter(imgDownGroup)
                SDWebImageManager.sharedManager().downloadImageWithURL(url, options: SDWebImageOptions(rawValue: 0), progress: nil, completed: { (_, _, _, _, _) in
                    // 完成图片下载 离开当前『组』
                    dispatch_group_leave(imgDownGroup)
                })
            }
        }
        
        // 使用图片都下载完成后，通过传入的闭包参数通知调用者
        dispatch_group_notify(imgDownGroup, dispatch_get_main_queue()) { 
            finished(model: modelList, error: nil)
        }
    }
    
    /**
     将返回的JSON数据转换为模型
     */
    class func dictToModels(list: [[String: AnyObject]]) -> [Status]
    {
        var models = [Status]()
        for dict in list
        {
            models.append(Status(dict: dict))
        }
        return models
    }
    
    init(dict: [String: AnyObject])
    {
        super.init()
        setValuesForKeysWithDictionary(dict)
    }
    
    // 当调用 setValuesForKeysWithDictionary(dict) 时，会调用此方法
    override func setValue(value: AnyObject?, forKey key: String) {
        // 重写此方法，拦截当key为User时
        if key == "user"
        {
            user = User(dict: value as! [String: AnyObject])
            return
        }
        // 判断是否是转发微博
        if key  == "retweeted_status"
        {
            retweeted_status = Status(dict: value as! [String: AnyObject])
            return
        }
        
        if key == "created_at"
        {
//            print(value)
        }
        
        
        // 调用父类方法, 按照系统默认处理
        super.setValue(value, forKey: key)
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        
    }
    
    // 打印模型
    var keyArr = ["created_at", "id", "text", "source", "pic_urls"]
    override var description: String
    {
        let dict = dictionaryWithValuesForKeys(keyArr)
        return "\(dict)"
    }
}
